#include "stdafx.h"

#include "SearcheableFileFactory.h"
#include "SearcheableTXTFile.h"
#include "SearcheableHTMLFile.h"
#include "IndexedTXTFile.h"

#include <string>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/algorithm/string.hpp>

SearcheableFileFactory::SearcheableFileFactory(std::string& pathToDir)
{
	
	indexMap = IndexMap::load(pathToDir);
	if (indexMap==NULL)
	{
		indexExist = false;
	}
	else
	{
		indexExist = true;
	}
}

SearcheableFileFactory::~SearcheableFileFactory()
{
	delete(indexMap);
}

ISearcheableFile* SearcheableFileFactory::createSearcheableFile(std::string& pathToFile) 
{	
	if(ISearcheableFile::isApplicableForSearch(pathToFile))
	{
		if (indexExist)
		{
			if (indexMap->containsIndex(pathToFile))
			{
				return new IndexedTXTFile(pathToFile, (*indexMap));
			}
			else
			{
				indexExist=false;
			}
		}

		std::string fileExtension = boost::filesystem3::extension(pathToFile);

		if (boost::iequals(".txt", fileExtension))
		{
			return new SearcheableTXTFile(pathToFile);
		} 
		if(boost::iequals(".html", fileExtension))
		{
			return new SearcheableHTMLFile(pathToFile);
		}
	}

	return NULL;
}